package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.ZnhjEntity;
import cn.com.connext.scrm.service.ActivityService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.TaskService;
import cn.com.connext.scrm.service.mapper.ZnhjService;
import cn.com.connext.scrm.utils.RedisUtils;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.req.PointQueryReq;
import cn.com.connext.scrm.web.rest.req.TaskCreateReq;
import cn.com.connext.scrm.web.rest.req.TaskPointReq;
import cn.com.connext.scrm.web.rest.req.TaskQueryReq;
import cn.com.connext.scrm.web.rest.vm.QueryIdVM;
import cn.com.connext.scrm.web.rest.vm.QuestionnaireVM;
import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeoutException;

/**
 * 积分商城 - 积分任务管理
 */
@RestController
@RequestMapping("/api/shopping/task")
public class TaskResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(TaskResource.class);

    @Autowired
    private TaskService taskService;
    @Autowired
    private ZnhjService znhjService;
    @Autowired
    private ActivityService activityService;

    @Autowired
    private RedisUtils redisUtils;

    public TaskResource() throws TimeoutException {
        super("Activity");
    }

    /**
     * 创建积分任务
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建积分任务", tags = {"积分任务列表"}, notes = "积分任务")
    public JsonResult create(@RequestBody TaskCreateReq req) {
        log.info("创建积分任务，入参req : {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.create(req);
    }

    /**
     * 更新积分任务
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新积分任务", tags = {"积分任务列表"}, notes = "更新积分任务")
    public JsonResult update(@RequestBody TaskCreateReq req) {
        log.info("更新积分任务，入参req : {}", JSON.toJSONString(req));
        if (req == null) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.update(req);
    }

//    /**
//     * 审核积分任务
//     */
//    @PostMapping("/audit")
//    @ApiOperation(value = "审核积分任务", tags = {"问答活动列表"}, notes = "审核积分任务")
//    public JsonResult audit(@RequestBody TaskAuditReq req) {
//        log.info("审核积分任务，入参req : {}", JSON.toJSONString(req));
//        if (null == req) {
//            throw new ServiceException(MyErrorCode.ERROR_INPUT);
//        }
//        return taskService.audit(req);
//    }

    /**
     * 积分任务列表
     */
    @PostMapping("/query")
    @ApiOperation(value = "积分任务列表-小程序", tags = {"积分任务列表"}, notes = "积分任务列表")
    public JsonResult pages(@RequestBody TaskQueryReq req) {
        log.info("积分任务列表，入参req : {}", JSON.toJSONString(req));
        return taskService.pages(req);
    }

    /**
     * 积分任务列表
     */
    @PostMapping("/queryByBack")
    @ApiOperation(value = "积分任务列表-后台管理", tags = {"积分任务列表"}, notes = "积分任务列表")
    public JsonResult pageList(@RequestBody TaskQueryReq req) {
        log.info("积分任务列表，入参req : {}", JSON.toJSONString(req));
        return taskService.pageList(req);
    }

    /**
     * 任务启用
     */
    @PostMapping("/enable")
    @Timed
    @ApiOperation(value = "任务启用", tags = {"任务启用"}, notes = "任务启用")
    public JsonResult answerenable(@RequestBody QueryIdVM req) {
        log.info("活动启用入参req={}", JSON.toJSONString(req));
        JsonResult result = new JsonResult();
        try {
            result = taskService.enable(req);
            return result;
        } catch (Exception e) {
            log.error("启用失败:{}", e);
            result.setState(1);
            result.setMessage("启用失败");
            return result;
        }
    }

    /**
     * 积分任务详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "积分任务详情", tags = {"积分任务详情"}, notes = "积分任务详情")
    public JsonResult detail(@RequestBody QueryIdVM req) {
        log.info("积分任务详情，入参req : {}", JSON.toJSONString(req));
        return taskService.detail(req.getId());
    }

    /**
     * 每日签到
     */
    @PostMapping("/daily")
    @Timed
    @ApiOperation(value = "积分商城-每日签到", tags = {"积分任务管理"}, notes = "积分商城-积分任务删除")
    public JsonResult daily(@RequestBody TaskPointReq req) {
        log.info("每日签到入参req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.daily(req);
    }

    /**
     * 发帖 每日三次  每月20次
     */
    @PostMapping("/notes")
    @Timed
    @ApiOperation(value = "积分商城-发帖任务", tags = {"积分任务管理"}, notes = "积分商城-发帖任务")
    public JsonResult notes(@RequestBody TaskPointReq req) {
        log.info("积分商城-发帖任务=入参req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.notes(req);
    }

    /**
     * 评论活动
     * 成功发表评论，每日上限记3次，每月上限记20次
     */
    @PostMapping("/comment")
    @Timed
    @ApiOperation(value = "积分商城-评论任务", tags = {"积分任务管理"}, notes = "积分商城-评论任务")
    public JsonResult comment(@RequestBody TaskPointReq req) {
        log.info("积分商城-评论任务req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.comment(req);
    }

    /**
     *识别有效阅读行为，每日上限记5次
     */
    @PostMapping("/browseRecord")
    @Timed
    @ApiOperation(value = "积分商城-有效阅读", tags = {"积分任务管理"}, notes = "积分商城-有效阅读")
    public JsonResult browseRecord(@RequestBody TaskPointReq req) {
        log.info("积分商城-有效阅读req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.browseRecord(req);
    }

    /**
     *上传、修改头像 共两次可修改机会
     */
    @PostMapping("/updateImage")
    @Timed
    @ApiOperation(value = "积分商城-上传、修改头像", tags = {"积分任务管理"}, notes = "积分商城-上传、修改头像")
    public JsonResult updateImage(@RequestBody TaskPointReq req) {
        log.info("积分商城-上传、修改头像req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.updateImage(req);
    }

    /**
     *转发  成功转发，每日上限记3次，每月上限记20次
     */
    @PostMapping("/repeat")
    @Timed
    @ApiOperation(value = "积分商城-转发任务", tags = {"积分任务管理"}, notes = "积分商城-转发任务")
    public JsonResult repeat(@RequestBody TaskPointReq req) {
        log.info("积分商城-转发任务req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getMembershipId())||StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.repeat(req);
    }

    /**
     * 精华帖 每月一次
     */
    @PostMapping("/essences")
    @Timed
    @ApiOperation(value = "积分商城-精华帖任务", tags = {"积分任务管理"}, notes = "积分商城-精华帖任务")
    public JsonResult essences(@RequestBody TaskPointReq req) {
        log.info("积分商城-精华帖任务req={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.essences(req);
    }

    /**
     * 入会礼/完善会员信息
     */
    @PostMapping("/membership")
    @Timed
    @ApiOperation(value = "积分商城-入会礼/完善会员信息", tags = {"积分任务管理"}, notes = "积分商城-入会礼/完善会员信息")
    public JsonResult membership(@RequestBody TaskPointReq req) {
        log.info("积分商城-入会礼/完善会员信息={}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getId()) || StringUtils.isEmpty(req.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        return taskService.membership(req);
    }

    @PostMapping("/point")
    @Timed
    @ApiOperation(value = "积分列表", tags = {"积分列表"}, notes = "积分列表")
    public JsonResult pointList(@RequestBody PointQueryReq req) {
        return taskService.pointList(req);
    }

    /**
     * 权限埋点
     */

    /**
     * 会员等级经验列表
     */
    @PostMapping("/queryExperience")
    @ApiOperation(value = "获取会员成长值经验列表", tags = "获取会员成长值经验列表", notes = "获取会员成长值经验列表")
    public JsonResult queryExperience() {
        log.info("获取会员成长值经验列表");
        JsonResult result = taskService.queryExperience();
        return result;
    }



    /**
     * 检验提交码
     */
    @ApiOperation(value = "检验提交码", notes = "检验提交码")
    @PostMapping(value = "/checkCode")
    public JsonResult isActivate(@RequestBody ZnhjEntity sti ){
        JsonResult jsonResult =new JsonResult();
        try{
            if(StringUtils.isNotEmpty(sti.getUniqueCode())&&StringUtils.isNotEmpty(sti.getBottleCode())){
                log.info("bottleCode:{}",sti.getBottleCode());
                log.info("unionCode:{}",sti.getUniqueCode());
                if(sti.getUniqueCode().length() !=8 || !isNumeric(sti.getUniqueCode())){
                    jsonResult.setState(1);
                    jsonResult.setMessage("此数字唯一码无效(数字码查询不到&数字码与二维码不对应)");
                }else{
                    ZnhjEntity is =znhjService.findByUniqueCodeAndBottomCode(sti.getUniqueCode(),sti.getBottleCode());
                    if(is ==null ){
                        jsonResult.setState(1);
                        jsonResult.setMessage("此数字唯一码无效(数字码查询不到&数字码与二维码不对应)");
                    }else{
                        //该二维码是否被使用
                        Integer count =znhjService.isActivate(sti.getUniqueCode());
                        if(count == 1){
                            jsonResult.setState(1);
                            jsonResult.setMessage("此二维码已使用(二维码已经抽过积分)");
                        }else{
                            StringBuilder sb = new StringBuilder(sti.getBottleCode());
                            sb.append(sti.getUniqueCode());
                            String key = sb.toString();
                            Boolean resultRedis = redisUtils.setIfAbsent(key, key);
                            log.info("resultRedis={}", resultRedis);
                            if(resultRedis) {
                                try {
                                    return taskService.scanCode(sti);
                                }catch (Exception e){
                                    jsonResult.setState(500);
                                    jsonResult.setMessage("操作异常");
                                    log.error("e:{}",e);
                                }finally {
                                    redisUtils.remove(key);
                                }
                            }
                        }
                    }
                }
            }else{
                jsonResult.setState(1);
                jsonResult.setMessage("提交信息异常");
            }
        }catch (Exception e){
            jsonResult.setState(500);
            jsonResult.setMessage("操作异常");
            log.error("e:{}",e);
        }
        return  jsonResult;
    }


    public final static boolean isNumeric(String str){
        if (str != null && !"".equals(str.trim())){
            return str.matches("^[0-9]*$");
        }
        else{
            return false;
        }
    }


    @PostMapping("/queryQuestionnaireByUnionId")
    @Timed
    @ApiOperation(value = "查询用户问卷是否完成", tags = {"查询用户问卷是否完成"}, notes = "查询用户问卷是否完成")
    public JsonResult queryQuestionnaireByUnionId(@RequestBody QuestionnaireVM vm) {
        JsonResult result = new JsonResult();
        try{
            log.info("查看问卷用户unionId="+vm.getUnionId());
            result = taskService.queryQuestionnaireByUnionId(vm);
        }catch (Exception e){
            result.setState(500);
            result.setMessage("系统异常");
            log.error("e:{}",e);
        }
        return result;
    }

    @PostMapping("/recordQuestionnaire")
    @Timed
    @ApiOperation(value = "记录用户问卷完成", tags = {"记录用户问卷完成"}, notes = "记录用户问卷完成")
    public JsonResult recordQuestionnaire(@RequestBody QuestionnaireVM vm) {
        JsonResult result = new JsonResult();
        try{
            log.info("记录用户问卷完成unionId="+vm.getUnionId());
            result = taskService.questionnaireFinish(vm);
        }catch (Exception e){
            result.setState(500);
            result.setMessage("系统异常");
            log.error("e:{}",e);
        }
        return result;
    }
}
